
 <!DOCTYPE HTML>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  
    <title>玩转Angular2(6)--模型驱动和模板驱动的表单 | Here. There.</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=3, minimum-scale=1">
    
    <meta name="author" content="被删">
    
    <meta name="description" content="因为项目原因又玩上了Angular2(v4.0+)，《玩转Angular2》系列用于探索一些灵活或者新的用法。本文简单介绍模型驱动和模板驱动的表单，以及一些表单验证。">
    
    
    
    
    <link rel="alternate" href="/atom.xml" title="Here. There." type="application/atom+xml">
    
    
    <link rel="icon" href="/img/favicon.ico">
    
    
    <link rel="apple-touch-icon" href="/img/pacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/img/pacman.jpg">
    
    <link rel="stylesheet" href="/css/style.css">
    
<script type="text/javascript">
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?3d902de4a19cf2bf179534ffd2dd7b7f";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>

</head>

  <body>
    <header>
      <div>
		
			<div id="imglogo">
				<a href="/"><img src="/img/sun.png" alt="Here. There." title="Here. There."/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/" title="Here. There.">Here. There.</a></h1>
				<h2 class="blog-motto">Love ice cream. Love sunshine. Love life. Love the world. Love myself. Love you.</h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="菜单">
			</a></div>
			<nav class="animated">
				<ul>
					
						<li><a href="/">首页</a></li>
					
						<li><a href="https://github.com/godbasin/godbasin.github.io">所有文章</a></li>
					
						<li><a href="/archives">归档</a></li>
					
						<li><a href="/categories">分类</a></li>
					
						<li><a href="/about">关于我</a></li>
					
				</ul>
			</nav>			
</div>

    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/2017/06/04/angular2-free-6-two-form-building/" title="玩转Angular2(6)--模型驱动和模板驱动的表单" itemprop="url">玩转Angular2(6)--模型驱动和模板驱动的表单</a>
  </h1>
  <p class="article-author">By
    
      <a href="https://godbasin.github.io" title="被删">被删</a>
    </p>
  <p class="article-time">
    <time datetime="2017-06-04T09:32:02.000Z" itemprop="datePublished">2017-06-04</time>
    更新日期:<time datetime="2018-12-18T15:31:30.938Z" itemprop="dateModified">2018-12-18</time>
    
  </p>
</header>
	<div class="article-content">
		
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">文章目录</strong>
		<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Angular2表单"><span class="toc-number">1.</span> <span class="toc-text">Angular2表单</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#模板驱动"><span class="toc-number">1.1.</span> <span class="toc-text">模板驱动</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#模型驱动"><span class="toc-number">1.2.</span> <span class="toc-text">模型驱动</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#结束语"><span class="toc-number">2.</span> <span class="toc-text">结束语</span></a></li></ol>
		</div>
		
		<p>因为项目原因又玩上了Angular2(v4.0+)，《玩转Angular2》系列用于探索一些灵活或者新的用法。<br>本文简单介绍模型驱动和模板驱动的表单，以及一些表单验证。<br><a id="more"></a></p>
<h2 id="Angular2表单"><a href="#Angular2表单" class="headerlink" title="Angular2表单"></a>Angular2表单</h2><hr>
<h3 id="模板驱动"><a href="#模板驱动" class="headerlink" title="模板驱动"></a>模板驱动</h3><p>很多时候我们都会使用模板驱动的表单，因为很方便。<br>使用Angular模板语法编写模板，便是模板驱动的表单。</p>
<ol>
<li>FormModule</li>
</ol>
<p>使用模板驱动的一些模板语法，我们需要引入<code>FormModule</code>:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> &#123; FormsModule &#125; <span class="keyword">from</span> <span class="string">'@angular/forms'</span>;</div></pre></td></tr></table></figure>
<p>这样，我们的<code>&lt;form&gt;</code>和<code>&lt;input&gt;</code>等表单元素便是Angular元素，拥有了像<code>ngModel</code>、<code>ngSubmit</code>等指令或属性。</p>
<ol>
<li>模板驱动的表单</li>
</ol>
<p>这里我们使用最简单的<code>input</code>，需要输入一个3-8字符的名字。Component中的js代码几乎没多少，而html模板如下：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">class</span>=<span class="string">"form-horizontal"</span> #<span class="attr">form</span>=<span class="string">"ngForm"</span> (<span class="attr">ngSubmit</span>)=<span class="string">"submit()"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"form-group"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">label</span> <span class="attr">class</span>=<span class="string">"col-md-2 control-label"</span>&gt;</span>name<span class="tag">&lt;/<span class="name">label</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"col-md-6"</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">"form-control"</span> <span class="attr">type</span>=<span class="string">"text"</span></span></div><div class="line">                   [(<span class="attr">ngModel</span>)]=<span class="string">"model.name"</span> <span class="attr">name</span>=<span class="string">"name"</span></div><div class="line">                   <span class="attr">required</span> <span class="attr">maxlength</span>=<span class="string">"8"</span> <span class="attr">minlength</span>=<span class="string">"3"</span></div><div class="line">                   #<span class="attr">name</span>=<span class="string">"ngModel"</span> /&gt;</div><div class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"alert alert-danger col-md-6 col-md-offset-2"</span> *<span class="attr">ngIf</span>=<span class="string">"name.errors &amp;&amp; (name.dirty || name.touched)"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">p</span> [<span class="attr">hidden</span>]=<span class="string">"!name.errors.required"</span>&gt;</span>必填<span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">p</span> [<span class="attr">hidden</span>]=<span class="string">"!name.errors.minlength"</span>&gt;</span>不小于3个字符<span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">p</span> [<span class="attr">hidden</span>]=<span class="string">"!name.errors.maxlength"</span>&gt;</span>不大于8个字符<span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"form-group"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"col-sm-offset-2 col-sm-10"</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">button</span> [<span class="attr">disabled</span>]=<span class="string">"!form.valid"</span> <span class="attr">type</span>=<span class="string">"submit"</span> <span class="attr">class</span>=<span class="string">"btn btn-info"</span>&gt;</span>提交<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div><div class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<ul>
<li>通过<code>ngModel</code>跟踪修改状态与有效性验证</li>
</ul>
<p>在表单中使用<code>ngModel</code>可以获得比仅使用双向数据绑定更多的控制权，不仅仅跟踪状态。它还使用特定的Angular CSS类来更新控件，以反映当前状态。<br>可以利用这些CSS类来修改控件的外观，显示或隐藏消息。</p>
<ul>
<li><code>required</code>/<code>maxlength</code>/<code>minlength</code>: 用于表单校验<ul>
<li><code>name.touched</code>: 控件被访问过</li>
<li><code>name.dirty</code>: 控件的值变化了</li>
<li><code>name.errors</code>: 控件校验错误</li>
</ul>
</li>
</ul>
<p>指向<code>input</code>控件的引用变量上的<code>valid</code>属性，可用于检查控件是否有效、是否显示/隐藏错误信息。</p>
<ul>
<li><code>#name=&quot;ngModel&quot;</code></li>
</ul>
<p><code>#name</code>是模板引用变量。使用井号(<code>#</code>)来声明引用变量。<br>模板引用变量通常用来引用模板中的某个DOM元素，它还可以引用Angular组件或指令或Web Component。</p>
<p>指令的<code>exportAs</code>属性告诉Angular如何链接模板引用变量到指令。<br>这里把<code>name</code>设置为<code>ngModel</code>是因为<code>ngModel</code>指令的<code>exportAs</code>属性设置成了”ngModel”。<br><code>name</code>属性的用途是有效性验证和对表单元素的变更进行追踪。</p>
<ul>
<li>使用<code>ngSubmit</code>提交该表单</li>
</ul>
<p>按钮位于表单的底部，它自己不做任何事，但因为有<code>type=&quot;submit&quot;</code>，所以会触发表单提交。<br>而要使得表单提交生效，需要把该表单的<code>ngSubmit</code>事件属性绑定到对应的提交事件。</p>
<p>如果需要校验，则需要添加<code>#form=&quot;ngForm&quot;</code>，将<code>form</code>变量<code>exportAs</code>属性设置成<code>ngForm</code>，可跟踪表单有效性验证：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">class</span>=<span class="string">"form-horizontal"</span> #<span class="attr">form</span>=<span class="string">"ngForm"</span> (<span class="attr">ngSubmit</span>)=<span class="string">"submit()"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">button</span> [<span class="attr">disabled</span>]=<span class="string">"!form.valid"</span> <span class="attr">type</span>=<span class="string">"submit"</span> <span class="attr">class</span>=<span class="string">"btn btn-info"</span>&gt;</span>提交<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<h3 id="模型驱动"><a href="#模型驱动" class="headerlink" title="模型驱动"></a>模型驱动</h3><p>模型驱动表单又称为响应式表单，它将在html上的一些模板语法迁移到js中使用。<br>Angular的响应式表单能让实现响应式编程风格更容易，这种编程风格更倾向于在非UI的数据模型（通常接收自服务器）之间显式的管理数据流，并且用一个UI导向的表单模型来保存屏幕上HTML控件的状态和值。响应式表单可以让使用响应式编程模式、测试和校验变得更容易。</p>
<p>简单地说，就是模型驱动表单更加灵活，值和状态的同步更新，以及测试性较好。</p>
<ol>
<li>异步 vs. 同步</li>
</ol>
<p>响应式表单是同步的。模板驱动表单是异步的。</p>
<p>模板驱动表单会委托指令来创建它们的表单控件。<br>使用响应式表单，我们会在代码中创建整个表单控件树。 我们可以立即更新一个值或者深入到表单中的任意节点，因为所有的控件都始终是可用的。</p>
<ol>
<li>ReactiveFormsModule</li>
</ol>
<p>使用模型驱动的一些模板语法，我们需要引入<code>ReactiveFormsModule</code>:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> &#123; ReactiveFormsModule &#125; <span class="keyword">from</span> <span class="string">'@angular/forms'</span>;</div></pre></td></tr></table></figure>
<ol>
<li>基础的表单类</li>
</ol>
<ul>
<li><code>AbstractControl</code><ul>
<li>是三个具体表单类的抽象基类</li>
<li>为它们提供了一些共同的行为和属性，其中有些是可观察对象（<code>Observable</code>）。</li>
</ul>
</li>
<li><code>FormControl</code><ul>
<li>用于跟踪一个单独的表单控件的值和有效性状态</li>
<li>它对应于一个HTML表单控件，比如输入框和下拉框</li>
</ul>
</li>
<li><code>FormGroup</code><ul>
<li>用于跟踪一组<code>AbstractControl</code>的实例的值和有效性状态</li>
<li>该组的属性中包含了它的子控件</li>
<li>组件中的顶级表单就是一个<code>FormGroup</code></li>
</ul>
</li>
<li><code>FormArray</code><ul>
<li>用于跟踪<code>AbstractControl</code>实例组成的有序数组的值和有效性状态</li>
</ul>
</li>
</ul>
<ol>
<li><code>FormGroup</code></li>
</ol>
<p>有多个<code>FormControl</code>，把它们注册进一个父<code>FormGroup</code>中：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">reactiveForm = <span class="keyword">new</span> FormGroup (&#123;</div><div class="line">    <span class="attr">name</span>: <span class="keyword">new</span> FormControl(),</div><div class="line">    <span class="attr">email</span>: <span class="keyword">new</span> FormControl(),</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>将<code>formGroup</code>关联到的是<code>form</code>元素上的<code>FormGroup</code>实例reactiveForm：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">class</span>=<span class="string">"form-horizontal"</span> [<span class="attr">formGroup</span>]=<span class="string">"reactiveForm"</span> (<span class="attr">ngSubmit</span>)=<span class="string">"submit()"</span>&gt;</span></div></pre></td></tr></table></figure>
<p><code>formGroup</code>是一个响应式表单的指令，它拿到一个现有<code>FormGroup</code>实例，并把它关联到一个HTML元素上。</p>
<ol>
<li>formControlName</li>
</ol>
<p>有了<code>FormGroup</code>，<code>name</code>输入框就需要再添加一个语法<code>formControlName=&quot;name&quot;</code>，以便让它关联到类中正确的<code>FormControl</code>上：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"form-group"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">label</span> <span class="attr">class</span>=<span class="string">"col-md-2 control-label"</span>&gt;</span>name<span class="tag">&lt;/<span class="name">label</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"col-md-6"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">"form-control"</span> <span class="attr">formControlName</span>=<span class="string">"name"</span> /&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div></pre></td></tr></table></figure>
<p>这个语法告诉Angular，查阅父<code>FormGroup</code>，然后在这个<code>FormGroup</code>中查阅一个名叫<code>name</code>的<code>FormControl</code>。</p>
<ol>
<li>FormBuilder</li>
</ol>
<p><code>FormBuilder</code>类能通过处理控件创建的细节问题来帮我们减少重复劳动。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">constructor</span>(private fb: FormBuilder) &#123; <span class="comment">// 注入FormBuilder</span></div><div class="line">    <span class="keyword">this</span>.createForm();</div><div class="line">&#125;</div><div class="line"></div><div class="line">createForm() &#123;</div><div class="line">    <span class="keyword">this</span>.reactiveForm = <span class="keyword">this</span>.fb.group(&#123;</div><div class="line">        <span class="attr">name</span>: [<span class="string">''</span>, [</div><div class="line">            Validators.required,</div><div class="line">            Validators.minLength(<span class="number">3</span>),</div><div class="line">            Validators.maxLength(<span class="number">8</span>)</div><div class="line">        ]</div><div class="line">        ],</div><div class="line">        <span class="attr">email</span>: [<span class="string">''</span>,</div><div class="line">            [</div><div class="line">                Validators.required,</div><div class="line">                Validators.email</div><div class="line">            ]</div><div class="line">        ],</div><div class="line">    &#125;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><code>FormBuilder.group</code>是一个用来创建<code>FormGroup</code>的工厂方法，它接受一个对象，对象的键和值分别是<code>FormControl</code>的名字和它的定义。<br>每个<code>FormControl</code>的设置都是<code>FormControl</code>名字和数组值。第一个数组元素是控件对应的当前值，第二个值（可选）是验证器函数或者验证器函数数组。</p>
<p>大多数验证器函数是Angular以<code>Validators</code>类的静态方法的形式提供的原装验证器。</p>
<ol>
<li>valueChanges</li>
</ol>
<p>可以通过订阅表单控件的属性之一来了解表单控件变化。<br><code>valueChanges</code>返回一个RxJS的Observable对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">this</span>.reactiveForm.valueChanges</div><div class="line">    .subscribe(<span class="function"><span class="params">data</span> =&gt;</span> <span class="keyword">this</span>.onValueChanged(data));</div></pre></td></tr></table></figure>
<p>这里我们需要添加触发事件回调：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 定义表单错误</span></div><div class="line">formErrors = &#123;</div><div class="line">    <span class="attr">name</span>: <span class="string">''</span></div><div class="line">&#125;;</div><div class="line"><span class="comment">// 对表单错误做说明映射</span></div><div class="line">validationMessages = &#123;</div><div class="line">    <span class="attr">name</span>: &#123;</div><div class="line">        <span class="attr">required</span>: <span class="string">'名字必填'</span>,</div><div class="line">        <span class="attr">minlength</span>: <span class="string">'名字最少3个字符'</span>,</div><div class="line">        <span class="attr">maxlength</span>: <span class="string">'名字最多8个字符'</span></div><div class="line">    &#125;</div><div class="line">&#125;;</div><div class="line"><span class="comment">// 表单更新触发回调</span></div><div class="line">onValueChanged(data?: any) &#123;</div><div class="line">    <span class="keyword">if</span> (!<span class="keyword">this</span>.reactiveForm) &#123;</div><div class="line">        <span class="keyword">return</span>;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">const</span> form = <span class="keyword">this</span>.reactiveForm;</div><div class="line">    <span class="comment">// 遍历表单控件名字</span></div><div class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> field <span class="keyword">in</span> <span class="keyword">this</span>.formErrors) &#123;</div><div class="line">        <span class="keyword">this</span>.formErrors[field] = <span class="string">''</span>; <span class="comment">// 清除之前的错误信息</span></div><div class="line">        <span class="keyword">const</span> control = form.get(field);  <span class="comment">// 获取控件</span></div><div class="line">        <span class="keyword">if</span> (control &amp;&amp; control.dirty &amp;&amp; !control.valid) &#123;</div><div class="line">            <span class="comment">// 遍历获取错误说明</span></div><div class="line">            <span class="keyword">const</span> messages = <span class="keyword">this</span>.validationMessages[field];</div><div class="line">            <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> control.errors) &#123;</div><div class="line">                <span class="keyword">this</span>.formErrors[field] += messages[key] + <span class="string">' '</span>;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>最终效果图：</p>
<p><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/1495970774%281%29.png" alt="image"></p>
<h2 id="结束语"><a href="#结束语" class="headerlink" title="结束语"></a>结束语</h2><hr>
<p>讲到这里，我们的两种Angular表单–模型驱动和模板驱动，它们的简单使用和校验已经完成。<br>而需要更复杂一些的功能，像多级<code>FormGroup</code>、动态表单等，后面我们或许也会讲到。<br><a href="https://github.com/godbasin/godbasin.github.io/tree/blog-codes/angular2-free/6-two-form-building" target="_blank" rel="external">此处查看项目代码</a><br><a href="http://angular2-free.godbasin.com/6-two-form-building/index.html#/home/page-setting" target="_blank" rel="external">此处查看页面效果</a></p>
  
		
		<p style="margin-top:50px;">查看Github有更多内容噢：<a href="https://github.com/godbasin">https://github.com/godbasin</a></p>
	</div>
	<img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/2code2.jpg" width="200" height="200" style="display:block;margin: 0 auto;" />
	<p style="text-align: center;margin-top: 10px;margin-bottom: 20px;">码生艰难，写文不易，给我家猪囤点猫粮了喵~</p>
	<div class="author-right">
  		<p>作者：被删</p>
  		<p>出处：<a href="https://godbasin.github.io">https://godbasin.github.io</a></p>
  		<p>本文版权归作者所有，欢迎转载，但未经作者同意必须保留此段声明，且在文章页面明显位置给出原文连接，否则保留追究法律责任的权利。</p>
	</div>
		<footer class="article-footer clearfix">

  <div class="article-tags">
  
  <span></span> <a href="/tags/笔记/">笔记</a>
  </div>


<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/categories/angular2火锅/">angular2火锅</a>
</div>



<div class="article-share" id="share">

  
<!-- JiaThis Button BEGIN -->
<div class="jiathis_style_24x24">
	<a class="jiathis_button_qzone"></a>
	<a class="jiathis_button_tsina"></a>
	<a class="jiathis_button_tqq"></a>
	<a class="jiathis_button_weixin"></a>
	<a class="jiathis_button_renren"></a>
	<a href="http://www.jiathis.com/share?uid=2134021" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
</div>
<script type="text/javascript">
var jiathis_config = {data_track_clickback:'true'};
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code_mini/jia.js?uid=2134021" charset="utf-8"></script>
<!-- JiaThis Button END -->   


</div>
</footer>   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/2017/06/09/angular2-free-7-dynamic-form/" title="玩转Angular2(7)--创建动态表单">
  <strong>PREVIOUS:</strong><br/>
  <span>
  玩转Angular2(7)--创建动态表单</span>
</a>
</div>


<div class="next">
<a href="/2017/06/03/angular2-free-5-custom-input-component/"  title="玩转Angular2(5)--自定义input表单控件">
 <strong>NEXT:</strong><br/> 
 <span>玩转Angular2(5)--自定义input表单控件
</span>
</a>
</div>

</nav>

	<!-- 如果不是首页且没使用 `comments: false` 关闭评论，则尝试加载评论 -->

    <!-- 配置中启用多说时，导入相应代码 -->
    


</div>  
      <div class="openaside"><a class="navbutton" href="#" title="显示侧边栏"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">文章目录</strong>
  <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Angular2表单"><span class="toc-number">1.</span> <span class="toc-text">Angular2表单</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#模板驱动"><span class="toc-number">1.1.</span> <span class="toc-text">模板驱动</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#模型驱动"><span class="toc-number">1.2.</span> <span class="toc-text">模型驱动</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#结束语"><span class="toc-number">2.</span> <span class="toc-text">结束语</span></a></li></ol>
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="隐藏侧边栏"></a></div>
<aside class="clearfix">

  	
	<div class="archiveslist">
		<p class="asidetitle">最近文章</p>
			<ul class="archive-list">
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/07/11/vue-for-everyone-2/" title="9102全员学Vue--2.怎么三两下拼出一个页面">9102全员学Vue--2.怎么三两...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/06/30/about-front-end-2-principle/" title="前端这几年--2.工作原则和选择">前端这几年--2.工作原则和选择...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/06/27/vue-for-everyone-1/" title="9102全员学Vue--1.如何理解前端和Vue">9102全员学Vue--1.如何理解...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/06/17/wxapp-latest-20190617/" title="小程序开发月刊第六期（20190617）">小程序开发月刊第六期（2019061...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/06/17/wxapp-generate/" title="小程序的诞生">小程序的诞生</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/05/15/wxapp-latest-20190515/" title="小程序开发月刊第五期（20190515）">小程序开发月刊第五期（2019051...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/04/15/wxapp-latest-20190415/" title="小程序开发月刊第四期（20190415）">小程序开发月刊第四期（2019041...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/04/13/about-front-end-1-begin-in/" title="前端这几年--1.转岗之路">前端这几年--1.转岗之路...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/03/15/wxapp-latest-20190315/" title="小程序开发月刊第三期（20190315）">小程序开发月刊第三期（2019031...</a>
				</li>
				
			
					
				<li class="archive-list-item">
					<a class="archive-list-link" href="/2019/03/10/work-2-article/" title="写文章这件事">写文章这件事</a>
				</li>
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
				
			
			</ul>
	</div>


  
  <div class="archiveslist">
    <p class="asidetitle"><a href="/archives">归档</a></p>
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/07/">七月 2019</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/06/">六月 2019</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/05/">五月 2019</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/04/">四月 2019</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/03/">三月 2019</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/02/">二月 2019</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/01/">一月 2019</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/12/">十二月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/11/">十一月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/10/">十月 2018</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/09/">九月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/08/">八月 2018</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/07/">七月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/06/">六月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/05/">五月 2018</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/04/">四月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">三月 2018</a><span class="archive-list-count">7</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/02/">二月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/01/">一月 2018</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/12/">十二月 2017</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/11/">十一月 2017</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/10/">十月 2017</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/09/">九月 2017</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/08/">八月 2017</a><span class="archive-list-count">11</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/07/">七月 2017</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/06/">六月 2017</a><span class="archive-list-count">10</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/05/">五月 2017</a><span class="archive-list-count">15</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/04/">四月 2017</a><span class="archive-list-count">7</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/03/">三月 2017</a><span class="archive-list-count">10</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/02/">二月 2017</a><span class="archive-list-count">41</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/01/">一月 2017</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/12/">十二月 2016</a><span class="archive-list-count">7</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/11/">十一月 2016</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/10/">十月 2016</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/09/">九月 2016</a><span class="archive-list-count">7</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/08/">八月 2016</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/07/">七月 2016</a><span class="archive-list-count">14</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/06/">六月 2016</a><span class="archive-list-count">9</span></li></ul>
  </div>


  
<div class="archiveslist">
	<p class="asidetitle"><a href="/categories">分类</a></p>
		<ul class="archive-list">
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/CSS炒饭/" title="CSS炒饭">CSS炒饭<sup>3</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/D3小馒头/" title="D3小馒头">D3小馒头<sup>8</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/angular2火锅/" title="angular2火锅">angular2火锅<sup>25</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/angular混搭/" title="angular混搭">angular混搭<sup>33</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/box2djs方糖/" title="box2djs方糖">box2djs方糖<sup>34</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/cyclejs哈根达斯/" title="cyclejs哈根达斯">cyclejs哈根达斯<sup>8</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/jQuery杂烩/" title="jQuery杂烩">jQuery杂烩<sup>3</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/js什锦/" title="js什锦">js什锦<sup>26</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/react沙拉/" title="react沙拉">react沙拉<sup>16</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/three-js奶茶/" title="three.js奶茶">three.js奶茶<sup>5</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/vue八宝粥/" title="vue八宝粥">vue八宝粥<sup>28</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/webpack宾治/" title="webpack宾治">webpack宾治<sup>9</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/web乱炖/" title="web乱炖">web乱炖<sup>2</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/前端满汉全席/" title="前端满汉全席">前端满汉全席<sup>8</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/喵/" title="喵">喵<sup>1</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/小程序双皮奶/" title="小程序双皮奶">小程序双皮奶<sup>21</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/工作这杯茶/" title="工作这杯茶">工作这杯茶<sup>4</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/应用巧克力盒/" title="应用巧克力盒">应用巧克力盒<sup>2</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/思想棉花糖/" title="思想棉花糖">思想棉花糖<sup>8</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/柴米油盐工具集/" title="柴米油盐工具集">柴米油盐工具集<sup>1</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/categories/非前端钙片/" title="非前端钙片">非前端钙片<sup>7</sup></a>
			</li>
		
		</ul>
</div>


  
<div class="archiveslist">
	<p class="asidetitle">标签</p>
		<ul class="archive-list">
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/分享/" title="分享">分享<sup>44</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/原创部件/" title="原创部件">原创部件<sup>1</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/心态/" title="心态">心态<sup>4</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/教程/" title="教程">教程<sup>65</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/晒猫/" title="晒猫">晒猫<sup>1</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/笔记/" title="笔记">笔记<sup>121</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/算法/" title="算法">算法<sup>9</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/自制插件/" title="自制插件">自制插件<sup>2</sup></a>
			</li>
		
			<li class="archive-list-item">
				<a class="archive-list-link" href="/tags/逻辑实现/" title="逻辑实现">逻辑实现<sup>5</sup></a>
			</li>
		
		</ul>
</div>


    <div class="archiveslist">
    <p class="asidetitle"><a href="/archives">about</a></p>
      <ul class="archive-list">
      	<li class="archive-list-item">
      		<a>wangbeishan@163.com</a>
      		<a href="https://github.com/godbasin">github.com/godbasin</a>
      	</li>
      </ul>
  </div>

  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS 订阅</a>
</div>

</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<section class="info">
		<p> 即使梦想再小，却很伟大 ^_^ </p>
	</section>
	 
		<p class="copyright">Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/A-limon/pacman" target="_blank" title="Pacman">Pacman</a> © 2019 
		
		<a href="https://godbasin.github.io" target="_blank" title="被删">被删</a>
		
		</p>
</div>
</footer>
    <script src="/js/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else
    {
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      h  = $('article h2')
      ah = $('article h2'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  if(ah.length==0){
    t.css('display','none');
  }else{
    c.click(function(){
      ta.css('display', 'block').addClass('fadeIn');
    });
    o.click(function(){
      ta.css('display', 'none');
    });
    $(window).scroll(function(){
      ta.css("top",Math.max(140,320-$(this).scrollTop()));
    });
  };
});
</script>







  </body>
</html>
